package com.zjpavt.client.udp.udpservice;

import com.zjpavt.client.Connection;
import com.zjpavt.client.enums.ExtendDeviceEnum;
import com.zjpavt.client.extenddevice.loop.loopcontroller.LoopController;
import com.zjpavt.client.hal.Buzzer;
import com.zjpavt.client.hal.DeviceID;
import com.zjpavt.client.hal.ExtendDeviceManager;
import com.zjpavt.client.hal.SystemInnerTemperatureSensor;
import com.zjpavt.client.hal.network.NetworkManager;
import com.zjpavt.client.udp.UdpSender;
import com.zjpavt.client.util.ClientConfig;
import com.zjpavt.client.util.CmdUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  杭州 技术指标测量
 * @author zyc
 */
@Slf4j
public class HangzhouMeasureParameter implements UdpService {
    public String HOST_NAME = "192.168.1.255";
    public static final int PORT = 20192;

    @Override
    public void execute(byte[] commandBytes) {
        throw new IllegalArgumentException();
    }

    /**
     * <X> <X_devcieID>
     * <doorOpen>
     * @param command
     */
    @Override
    public void execute(String command) {

    }
//    private final static Pattern CHANGE_TIME_PATTERN = Pattern.compile("^deviceId=(?<deviceId>[0-9a-fA-F]{32}) deviceTime=(?<time>[0-9]*)$");
    private final static Pattern DEVICE_ID_PATTERN = Pattern.compile("^deviceId=(?<deviceId>[0-9a-fA-F]{32}).*$");
    private final static Pattern DEVICE_ID_PATTERN1
        = Pattern.compile("^control from=android id=(?<deviceId>[0-9a-fA-F]{32}) timestamp=(?<time>[0-9]{0,13})?$");

    @Override
    public void execute(String command, ChannelHandlerContext channel) {
        Matcher syncTimeMatcher = DEVICE_ID_PATTERN1.matcher(command);
        if (syncTimeMatcher.matches()) {
            String devcieIdReceived = syncTimeMatcher.group("deviceId");
            if (DeviceID.getINSTANCE().getDeviceIdCached().equals(devcieIdReceived)) {
//                String msg = "controlResponse id=" + devcieIdReceived + " timestamp=" + System.currentTimeMillis() + "\n";
//                UdpSender.sendUdpPacket(HOST_NAME, PORT, msg.getBytes());
//                channel.writeAndFlush(msg);
            }
            return;
        }
        syncTime(command,channel);
//        if (matcher.matches()) {
//            sendDelay();
//        }
//
//        if (matcher.matches()) {
//            sendTempature();
//        }
    }

    public void sendDelay() {
        String data = "device serial=" + DeviceID.getINSTANCE().getDeviceIdCached()
                      + " delay=" + pingHost(ClientConfig.SERVER_IP) + "\n";
        UdpSender.sendUdpPacket(getDestAddress(), PORT, data.getBytes());
    }

    public void sendTempature() {
        LoopController loopController = (LoopController)ExtendDeviceManager.getInstance().getExtendDevice(ExtendDeviceEnum.CIRCUIT);
        if (loopController == null) {
            return;
        }
        long beginTime = System.currentTimeMillis();
        loopController.getFormattedAllCurrentAndVoltage();
        long costTime = System.currentTimeMillis() - beginTime;
        String data = "device serial=" + DeviceID.getINSTANCE().getDeviceIdCached()
                      + " detect=" + SystemInnerTemperatureSensor.getInstance().getCurrTmp()
                      + " detectTime=" + costTime
                      + "\n";
        UdpSender.sendUdpPacket(getDestAddress(), PORT, data.getBytes());
    }

    private final static Pattern CHANGE_TIME_PATTERN = Pattern.compile("^timeSyncStart deviceId=(?<deviceId>[0-9a-fA-F]{32}) deviceTime=(?<time>[0-9]*)$");
    public void syncTime(String msg, ChannelHandlerContext channel) {
        Matcher changeTimeMatcher = CHANGE_TIME_PATTERN.matcher(msg.trim());
        //      修改系统时间
        if (changeTimeMatcher.matches()) {
            long oldTime = Long.parseLong(changeTimeMatcher.group("time"));
//            到下一秒的时间 ms
            long msRemain = 1000 - oldTime % 1000;
            long currentTime = 0;
            try {
                Thread.sleep(msRemain);
                CmdUtil.setDate(new Date(oldTime + msRemain));
                currentTime = System.currentTimeMillis();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String returnMsg = "timeSyncResult deviceId=" + DeviceID.getINSTANCE().getDeviceIdCached()
                               + " syncTime=" + changeTimeMatcher.group("time") + " newTime=" + (currentTime - msRemain);
            UdpSender.sendUdpPacket(getDestAddress(), PORT, returnMsg.getBytes());
            channel.writeAndFlush(returnMsg);
            return;
        }
    }

    /**
     *
     * @return
     */
    private long pingHost(String hostName) {
        try {
            InetAddress hostAddress = InetAddress.getByName(ClientConfig.SERVER_IP);
            long beginTime = System.currentTimeMillis();
            if (hostAddress.isReachable(1000)) {
                long pingTime = System.currentTimeMillis() - beginTime;
                return pingTime;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取目标的地址
     * @return
     */
    public String getDestAddress() {
        String destHostIp = NetworkManager.getInstance().getNetworkMap().get(NetworkManager.INTERFACE_ETH_0).getInterfaceAddress().getBroadcast().getHostAddress();
        return destHostIp;
    }

    public void setDestAddress(String HOST_NAME) {
        this.HOST_NAME = HOST_NAME;
    }
}
